/*
 * Copyright (C) 2011. JiangHongTiao <jjurco.sk_gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sk.lieskove.jianghongtiao.websearch.document.preprocessing.actions;

import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import sk.lieskove.jianghongtiao.common.utils.FileUtils;
import sk.lieskove.jianghongtiao.common.utils.PropertiesUtils;
import sk.lieskove.jianghongtiao.websearch.persistence.WebSearchResponse;

import java.io.File;
import java.io.IOException;

/**
 * Extract text from the PDF document
 * 
 * Created by: xjuraj
 * Date: 10/11/11
 * Time: 6:19 PM
 */
public class Pdf2Txt implements PreprocessAction {

    private Logger log = Logger.getLogger(Pdf2Txt.class);
    private PropertiesUtils pu = new PropertiesUtils(Pdf2Txt.class);

    @Override
    public WebSearchResponse preprocess(WebSearchResponse response) {
        if(response.getFile() == null){
            return response;
        }
        String content = null;
        try {
            File outFile = FileUtils.getTempFile("Pdf2txt_", "");
            PDDocument doc = PDDocument.load(response.getFile());
            PDFTextStripper strip = new PDFTextStripper("UTF-8");
            content = strip.getText(doc);
            doc.close();
            FileUtils.write(outFile, content);
            response.setFile(outFile);
        } catch (IOException ex) {
            log.error("I/O exception thrown when trying to transform text from "
                    + "PDF file:" + response.getFile());
        }
        return response;
    }
}
